package models

import (
	"gorm.io/gorm"
	"order_srv/basic/config"
	"time"
)

// 围栏表
type Fence struct {
	Id          uint32         `gorm:"column:id;type:int UNSIGNED;comment:围栏ID;primaryKey;not null;" json:"id"`
	UserId      int32          `gorm:"column:user_id;type:int;comment:用户ID;not null;" json:"user_id"`
	CityId      int32          `gorm:"column:city_id;type:int;comment:城市ID;not null;" json:"city_id"`
	Name        string         `gorm:"column:name;type:varchar(50);comment:围栏名称;not null;" json:"name"`
	Type        int32          `gorm:"column:type;type:int;comment:围栏类型:1:矩形 2:圆形 3:多边形;not null;" json:"type"`
	Latitude    float64        `gorm:"column:latitude;type:double;comment:纬度（圆形围栏中心点）;" json:"latitude"`
	Longitude   float64        `gorm:"column:longitude;type:double;comment:经度（圆形围栏中心点）;" json:"longitude"`
	Radius      float64        `gorm:"column:radius;type:double;comment:圆形围栏半径（米）;" json:"radius"`
	Coordinates string         `gorm:"column:coordinates;type:text;comment:多边形/矩形围栏坐标(JSON格式);" json:"coordinates"`
	Description string         `gorm:"column:description;type:varchar(200);comment:围栏描述;" json:"description"`
	Status      int32          `gorm:"column:status;type:int;comment:状态:1:启用 2:停用;not null;" json:"status"`
	CreatedAt   time.Time      `gorm:"column:created_at;type:datetime(3);comment:创建时间;not null;" json:"created_at"`
	UpdatedAt   time.Time      `gorm:"column:updated_at;type:datetime(3);comment:修改时间;not null;" json:"updated_at"`
	DeletedAt   gorm.DeletedAt `gorm:"column:deleted_at;type:datetime;comment:删除时间;" json:"deleted_at"`
}

func (f *Fence) TableName() string {
	return "fence"
}

// 坐标点结构
type Coordinate struct {
	Lat float64 `json:"lat"`
	Lng float64 `json:"lng"`
}

// 矩形围栏结构
type RectangleFence struct {
	NorthEast Coordinate `json:"north_east"` // 东北角坐标
	SouthWest Coordinate `json:"south_west"` // 西南角坐标
}

// 多边形围栏结构
type PolygonFence struct {
	Coordinates []Coordinate `json:"coordinates"` // 多边形顶点坐标
}

// 查询围栏
func (f *Fence) GetFenceById(fenceId int32) error {
	return config.DB.Where("id = ?", fenceId).Limit(1).Find(&f).Error
}

// 创建围栏
func (f *Fence) CreateFancy() error {
	return config.DB.Create(&f).Error
}

// 详情围栏
func (f *Fence) GetFenceDetail(fenceId int32) error {
	return config.DB.Where("id = ?", fenceId).First(&f).Error
}

// 删除围栏
func (f *Fence) DeleteFence(fenceId int32) error {
	return config.DB.Where("id = ?", fenceId).Delete(&f).Error
}

// 修改围栏
func (f *Fence) UpdateFence(fenceId int32) error {
	return config.DB.Where("id = ?", fenceId).Updates(&f).Error
}

// 根据城市ID查询围栏
func (f *Fence) GetFencesByCityId(cityId int32) ([]Fence, error) {
	var fences []Fence
	err := config.DB.Where("city_id = ? AND status = 1", cityId).Find(&fences).Error
	return fences, err
}

// 查询有效的围栏列表
func (f *Fence) GetActiveFences() ([]Fence, error) {
	var fences []Fence
	now := time.Now()

	query := config.DB.Where("status = 1")

	// 添加有效期检查（如果设置了有效期）
	query = query.Where("(valid_start IS NULL OR valid_start <= ?) AND (valid_end IS NULL OR valid_end >= ?)", now, now)

	err := query.Find(&fences).Error
	return fences, err
}

// 根据围栏类型查询
func (f *Fence) GetFencesByType(fenceType int32) ([]Fence, error) {
	var fences []Fence
	err := config.DB.Where("type = ? AND status = 1", fenceType).Find(&fences).Error
	return fences, err
}

type FenceList struct {
	Id          int32      `json:"id"`
	City        string     `json:"city"`
	Name        string     `json:"name"`
	Description string     `json:"description"`
	Status      int32      `json:"status"`
	Type        int32      `json:"type"`
	FenceLevel  int32      `json:"fence_level"`
	ValidStart  *time.Time `json:"valid_start"`
	ValidEnd    *time.Time `json:"valid_end"`
	CreatedAt   time.Time  `json:"created_at"`
}

// 展示围栏列表
func (f *Fence) ListFence() (listFace []*FenceList, err error) {
	err = config.DB.Model(&Fence{}).
		Select("fence.id, fence.name, fence.description, fence.status, fence.type, fence.fence_level, fence.valid_start, fence.valid_end, fence.created_at, city.city as city").
		Joins("left join city on fence.city_id = city.id").
		Find(&listFace).Error
	return listFace, err
}
